﻿using System;
using System.Collections.Generic;
using System.Text;
using Cms.Core.Infrastructure.Extension;
using Microsoft.Extensions.DependencyInjection;

namespace Cms.Core.Infrastructure.Dependency
{
  public sealed  class ServiceLocator
    {

        public readonly static ServiceLocator Instance = new ServiceLocator();
        private static IServiceProvider _provider;
        private ServiceLocator()
        {


        }


        /// <summary>
        /// 设置应用程序服务提供者
        /// </summary>
        public void SetApplicationServiceProvider(IServiceProvider provider)
        {
            provider.NotNull(nameof(provider));
            _provider = provider;
            
        }


        /// <summary>
        /// 获取 <see cref="ServiceLifetime.Scoped"/>生命周期的服务提供者
        /// </summary>
        public IServiceProvider ScopedProvider
        {
            get
            {
                IScopedServiceResolver scopedResolver = _provider.GetService<IScopedServiceResolver>();
                return scopedResolver != null && scopedResolver.ResolveEnabled
                    ? scopedResolver.ScopedProvider
                    : null;
            }
        }




     

        /// <summary>
        /// 得到服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>

        public T GetService<T>()
        {

        
            IScopedServiceResolver scopedResolver = _provider.GetService<IScopedServiceResolver>();
            if (scopedResolver != null && scopedResolver.ResolveEnabled)
            {
                return scopedResolver.GetService<T>();
            }
            return _provider.GetService<T>();
        }


        /// <summary>
        /// 获取当前是否处于<see cref="ServiceLifetime.Scoped"/>生命周期中
        /// </summary>
        /// <returns></returns>ss
        public static bool InScoped()
        {
            return Instance.ScopedProvider != null;
        }

    }
}
